package zzh.com.kangkenuo.utils;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import zzh.com.kangkenuo.activity.MainActivity;
import zzh.com.kangkenuo.newutlis.EventbusHelper;
import zzh.com.kangkenuo.newutlis.NetMsgEvent;

public class X5WebView extends WebView {
    private Context context;
    private ProgressBar progressBar;

    @SuppressLint("SetJavaScriptEnabled")
    public X5WebView(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
        this.context = arg0;
        this.setWebViewClient(new Client((AppCompatActivity) arg0));
        //this.setWebChromeClient(WebChromeClient);
        // WebStorage webStorage = WebStorage.getInstance();
        initWebViewSettings();
        this.getView().setClickable(true);
    }

    private class Client extends WebViewClient {
        public AppCompatActivity activity;

        public Client(AppCompatActivity activity) {
            this.activity = activity;
        }


        @Override
        public boolean shouldOverrideKeyEvent(WebView webView, KeyEvent keyEvent) {
            return super.shouldOverrideKeyEvent(webView, keyEvent);
        }

        /**
         * 防止加载网页时调起系统浏览器
         */
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            Log.e("url", url);
            if (url.contains("cashier.sandpay.com.cn/fastPay/quickPay")) {
                Toast.makeText(activity, "跳转至杉德支付", Toast.LENGTH_LONG).show();
                openLinkBySystem(activity, url);
            } else {
                final PayTask task = new PayTask(activity);
                final String ex = task.fetchOrderInfoFromH5PayUrl(url);
                if (!TextUtils.isEmpty(ex)) {
                    if (checkAliPayInstalled(activity)) {
                        new Thread(new Runnable() {
                            public void run() {
                                final H5PayResultModel result = task.h5Pay(ex,
                                        true);
                                if (!TextUtils.isEmpty(result.getReturnUrl())) {
                                    activity
                                            .runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    view.loadUrl(result.getReturnUrl());
                                                }
                                            });
                                } else {
                                    activity
                                            .runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    view.canGoBack();
                                                }
                                            });
                                }
                            }
                        }).start();
                    }
                } else if (url.contains("alipays://platformapi")) {
                    if (checkAliPayInstalled(activity)) {
                        openLinkBySystem(activity, url);
                        view.goBack();
                    } else {
                        Toast.makeText(activity, "您尚未安装支付宝", Toast.LENGTH_LONG).show();
                    }
                } else {
                    if (url.contains("https://t.alipayobjects.com/L1/71/100/and/alipay_wap_dc.apk")) {
                        if (checkAliPayInstalled(activity)) {
                            Toast.makeText(activity, "手机已安装支付宝,请打开", Toast.LENGTH_LONG).show();
                        } else {
                            openLinkBySystem(activity, url);
                        }
                    } else {
                        view.loadUrl(url);
                    }
                }
            }
            return true;
        }

    }

    /**
     * 通过包名 在应用商店打开应用
     *
     * @param packageName 包名
     */
    private void openApplicationMarket(MainActivity a, String packageName) {
        try {
            String str = "market://details?id=" + packageName;
            Intent localIntent = new Intent(Intent.ACTION_VIEW);
            localIntent.setData(Uri.parse(str));
            a.startActivity(localIntent);
        } catch (Exception e) {
            // 打开应用商店失败 可能是没有手机没有安装应用市场
            e.printStackTrace();
            Toast.makeText(a, "打开应用商店失败", Toast.LENGTH_SHORT).show();
            // 调用系统浏览器进入商城
            String url = "http://app.mi.com/detail/163525?ref=search";
            openLinkBySystem(a, url);
        }
    }

    /**
     * 调用系统浏览器打开网页
     *
     * @param url 地址
     */
    private void openLinkBySystem(AppCompatActivity a, String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        a.startActivity(intent);
    }

    /**
     * 判断是否安装支付宝
     *
     * @param context
     * @return
     */
    public boolean checkAliPayInstalled(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context
                .getPackageManager());
        return componentName != null;
    }


    private void initWebViewSettings() {
        WebSettings webSetting = this.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //设置webView里字体大小
        webSetting.setSupportZoom(true);
        webSetting.setTextZoom(100);
    }

    @Override
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        boolean ret = super.drawChild(canvas, child, drawingTime);
        canvas.save();
        /*Paint paint = new Paint();
        paint.setColor(0x7fff0000);
		paint.setTextSize(24.f);
		paint.setAntiAlias(true);
		if (getX5WebViewExtension() != null) {
			canvas.drawText(this.getContext().getPackageName() + "-pid:"
					+ android.os.Process.myPid(), 10, 50, paint);
			canvas.drawText(
					"X5  Core:" + QbSdk.getTbsVersion(this.getContext()), 10,
					100, paint);
		} else {
			canvas.drawText(this.getContext().getPackageName() + "-pid:"
					+ android.os.Process.myPid(), 10, 50, paint);
			canvas.drawText("Sys Core", 10, 100, paint);
		}
		canvas.drawText(Build.MANUFACTURER, 10, 150, paint);
		canvas.drawText(Build.MODEL, 10, 200, paint);
		canvas.restore();*/
        return ret;
    }

    public X5WebView(Context arg0) {
        super(arg0);
        setBackgroundColor(85621);
    }


}
